package org.mozhu.mboot.admin.system.auth.service;

import org.apache.commons.lang3.ArrayUtils;
import org.mozhu.mboot.admin.system.account.entity.User;
import org.mozhu.mboot.admin.system.account.service.UserService;
import org.mozhu.mboot.admin.system.auth.entity.UserAuth;
import org.mozhu.mboot.admin.system.auth.repository.UserAuthRepository;
import org.mozhu.mboot.core.data.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;

@Transactional
@Service("userAuthService")
public class UserAuthServiceImpl extends BaseService<UserAuth, Long> implements UserAuthService {

    @Autowired
    UserService userService;

    protected UserAuthRepository getBaseRepository() {
        return (UserAuthRepository) baseRepository;
    }

    @Override
    public UserAuth findByUserId(Long userId) {
        return getBaseRepository().findByUserId(userId);
    }

    @Override
    public void addUserAuth(Long[] userIds, UserAuth m) {
        if (m == null) {
            return;
        }
        if (m.getId() != null) {
            // update
            save(m);
            return;
        }
        if (ArrayUtils.isNotEmpty(userIds)) {
            for (Long userId : userIds) {
                User user = userService.findById(userId);
                if (user == null) {
                    continue;
                }
                // add and merge
                UserAuth auth = this.getBaseRepository().findByUserId(userId);
                if (auth == null) {
                    auth = new UserAuth();
                    auth.setUserId(userId);
                }
                auth.addRoleIds(m.getRoleIds());
                auth.addPermissionIds(m.getPermissionIds());
                save(auth);
            }
        }
    }

}
